<template>
  <el-dialog :title="title" v-model="innerVisible" width="800px" append-to-body>
    <el-form
      ref="homeownersContractRef"
      :model="contractForm"
      :rules="rules"
      label-width="130px"
      label-position="left"
    >
      <el-form-item label="房源状态" v-if="contractForm.id">
        <el-text>{{ getHouseStatusText(contractForm.houseStatus) }}</el-text>
      </el-form-item>

      <el-form-item
        label="产证编号"
        prop="houseCertificateNumber"
        style="width: 60%"
      >
        <el-input
          v-model="contractForm.houseCertificateNumber"
          v-trim
          placeholder="请输入"
          :disabled="isReadOnlyContract"
        />
      </el-form-item>

      <el-form-item label="合同周期" required style="width: 60%">
        <div class="flex gap-2">
          <el-form-item prop="contractStartTime" style="margin-bottom: 0; width: 48%">
            <el-date-picker
              v-model="contractForm.contractStartTime"
              type="date"
              placeholder="开始日期"
              value-format="YYYY-MM-DD"
              :disabled="isEditMode(contractForm.id)"
              style="width: 100%"
            />
          </el-form-item>
          <span class="flex items-center">~</span>
          <el-form-item prop="contractEndTime" style="margin-bottom: 0; width: 48%">
            <el-date-picker
              v-model="contractForm.contractEndTime"
              type="date"
              placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled="isEditMode(contractForm.id)"
              :disabled-date="
                isEditMode(contractForm.id)
                  ? undefined
                  : disabledDateForNewContract
              "
              style="width: 100%"
            />
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item label="产证面积(㎡)" prop="houseArea" style="width: 60%">
        <el-input
          v-model="contractForm.houseArea"
          v-trim
          placeholder="请输入"
          :disabled="isReadOnlyContract"
        />
      </el-form-item>

      <el-form-item label="完整地址" prop="address">
        <el-input
          v-model="contractForm.address"
          v-trim
          placeholder="请输入地址"
          :disabled="isReadOnlyContract"
        />
      </el-form-item>

      <el-form-item label="租金及管理费描述" prop="rentFeeDescribe">
        <div style="width: 100%">
          <el-text type="primary" size="small"
            >本信息只用于租赁合同配置参考,不会展示给业主和租客</el-text
          >
          <el-input
            v-model="contractForm.rentFeeDescribe"
            v-trim
            type="textarea"
            placeholder="请输入内容"
            style="margin-top: 8px; width: 100%"
            :disabled="isReadOnlyContract"
          />
        </div>
      </el-form-item>

      <el-form-item label="合同文件">
        <div class="flex gap-6" style="align-items: flex-start !important">
          <div
            class="flex-1"
            style="
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            "
          >
            <file-upload
              v-model="contractForm.contractFileVo"
              :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']"
              :limit="1"
              :showDownload="true"
              :showTip="false"
              title="租房合同"
              :disabled="isReadOnlyContract"
            />
          </div>
          <div
            class="flex-1"
            style="
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            "
          >
            <file-upload
              v-model="contractForm.managementFeeFileVo"
              :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']"
              :limit="1"
              :showDownload="true"
              :showTip="false"
              title="管理费合同"
              :disabled="isReadOnlyContract"
            />
          </div>
          <div
            class="flex-1"
            style="
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            "
          >
            <file-upload
              v-model="contractForm.handoverFileVo"
              :fileType="['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']"
              :limit="1"
              :showDownload="true"
              :showTip="false"
              title="交接文件"
              :disabled="isReadOnlyContract"
            />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end gap-2">
        <el-button @click="close">取消</el-button>
        <el-button
          type="warning"
          @click="renewalHomeownersReminderCl"
          v-hasPermi="['fang:homeowners:reminder']"
          v-show="isEditMode(contractForm.id)"
          >发送续期提醒</el-button
        >
        <el-button
          type="danger"
          @click="terminateContractCl"
          v-hasPermi="['fang:homeowners:terminatecontract']"
          v-show="canTerminate"
          >终止合同</el-button
        >
        <el-button
          type="primary"
          @click="saveHomeownersContractCl"
          v-hasPermi="['fang:homeowners:savecontract']"
          >保存合同</el-button
        >
      </div>
    </template>
  </el-dialog>

  <!-- 终止合同确认对话框 -->
  <el-dialog v-model="terminateVisible" title="终止合同确认" width="400px">
    <span>
      确定要终止此合同吗？终止后将不再发送相关续期提醒，合同状态将变为"无效"，该操作不可撤销，请谨慎操作。
    </span>
    <template #footer>
      <el-button @click="terminateVisible = false">取消</el-button>
      <el-button type="danger" @click="handleTerminate">确认终止</el-button>
    </template>
  </el-dialog>

  <!-- 续期提醒确认对话框 -->
  <el-dialog v-model="reminderVisible" title="续期提醒" width="500px">
    <div class="whitespace-pre-wrap">{{ reminderContent }}</div>
    <template #footer>
      <el-button @click="reminderVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirmReminder">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import auth from "@/plugins/auth";
import {
  getHomeownersContract,
  terminateHomeownersContract,
  deleteDraftHomeownersContract,
  saveDraftHomeownersContract,
  saveHomeownersContract,
  getHomeownersReminder,
  confirmHomeownersReminder,
} from "@/api/fang/homeowners";
import FileUpload from "@/components/FileUpload/index.vue";
import { getFileObj } from "@/utils/tools";
import { getHouseStatusText, HOUSE_STATUS } from "@/utils/enums";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  homeownerId: { type: [Number, String], required: true },
  contractId: { type: [Number, String], default: null },
});
const emit = defineEmits([
  "update:modelValue",
  "saved",
  "deleted",
  "terminated",
  "closed",
]);

const innerVisible = ref(false);
watch(
  () => props.modelValue,
  (v) => (innerVisible.value = v),
  { immediate: true }
);
watch(innerVisible, (v) => emit("update:modelValue", v));

const title = ref("");
const loading = ref(false);
const contractForm = reactive({});
const homeownersContractRef = ref(null);
const terminateVisible = ref(false);
const reminderVisible = ref(false);
const reminderContent = ref("");
const reminderData = ref(null);

const isEditMode = (id) => id != null && id !== undefined;

// 只读：无保存合同权限则禁用
const isReadOnlyContract = computed(
  () => !auth.hasPermi("fang:homeowners:savecontract")
);

const canTerminate = computed(() => {
  return !!contractForm.id && contractForm.houseStatus !== HOUSE_STATUS.OFFLINE;
});

const disabledDateForNewContract = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  if (contractForm.contractStartTime) {
    const startDate = new Date(contractForm.contractStartTime);
    startDate.setHours(0, 0, 0, 0);
    if (time.getTime() < startDate.getTime()) return true;
  }
  if (time.getTime() < today.getTime()) return true;
  return false;
};

const rules = reactive({
  houseCertificateNumber: [
    { required: true, message: "产证编号不能为空", trigger: "blur" },
  ],
  houseArea: [
    { required: true, message: "产证面积不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字", trigger: "blur" },
  ],
  address: [{ required: true, message: "完整地址不能为空", trigger: "blur" }],
  contractStartTime: [
    { required: true, message: "请选择合同开始日期", trigger: "change" },
  ],
  contractEndTime: [
    { required: true, message: "请选择合同结束日期", trigger: "change" },
  ],
});

function resetContract() {
  Object.assign(contractForm, {
    id: null,
    homeownersId: null,
    houseNumber: null,
    contractStartTime: null,
    contractEndTime: null,
    houseArea: null,
    houseCertificateNumber: null,
    address: null,
    rentFeeDescribe: null,
    houseDescribe: null,
    contractFileVo: [],
    managementFeeFileVo: [],
    handoverFileVo: [],
  });
}

function close() {
  innerVisible.value = false;
  emit("closed");
}

function loadIfEdit() {
  if (!props.contractId) {
    title.value = "新增委托合同";
    resetContract();
    return;
  }
  loading.value = true;
  getHomeownersContract(props.contractId)
    .then((response) => {
      Object.assign(contractForm, response.data);
      contractForm.contractFileVo = getFileObj(response.data.contractFileVo);
      contractForm.managementFeeFileVo = getFileObj(
        response.data.managementFeeFileVo
      );
      contractForm.handoverFileVo = getFileObj(response.data.handoverFileVo);
      contractForm.contractStartTime = response.data.contractStartTime;
      contractForm.contractEndTime = response.data.contractEndTime;
      title.value = "编辑委托合同";
    })
    .finally(() => {
      loading.value = false;
    });
}

watch(
  () => props.contractId,
  () => loadIfEdit(),
  { immediate: true }
);

function renewalHomeownersReminderCl() {
  if (!contractForm.id) return;
  loading.value = true;
  getHomeownersReminder(contractForm.id)
    .then((response) => {
      reminderData.value = response.data;
      reminderContent.value = response.data.orgMessageContent || "";
      reminderVisible.value = true;
    })
    .catch(() => {
      // 错误处理已在 request 拦截器中统一处理
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleConfirmReminder() {
  if (!reminderData.value || !contractForm.id) return;
  const data = {
    contractUrl: reminderData.value.contractUrl,
    homeownerContractId: contractForm.id,
    leaseContractId: contractForm.leaseContractId || 0,
    orgMessageContent: reminderData.value.orgMessageContent,
  };
  loading.value = true;
  confirmHomeownersReminder(data)
    .then(() => {
      ElMessage.success("已发送提醒");
      reminderVisible.value = false;
      reminderData.value = null;
      reminderContent.value = "";
    })
    .catch(() => {
      // 错误处理已在 request 拦截器中统一处理
    })
    .finally(() => {
      loading.value = false;
    });
}

function terminateContractCl() {
  if (!contractForm.id) return;
  terminateVisible.value = true;
}

function handleTerminate() {
  if (!contractForm.id) return;
  terminateHomeownersContract(contractForm.id).then(() => {
    ElMessage.success("终止合同成功");
    emit("terminated");
    resetContract();
    terminateVisible.value = false;
    close();
  });
}

function saveHomeownersContractCl() {
  if (!homeownersContractRef.value) return;

  homeownersContractRef.value.validate((valid) => {
    if (!valid) return;
    const contractFileVo = contractForm.contractFileVo?.[0] ?? {};
    const managementFeeFileVo = contractForm.managementFeeFileVo?.[0] ?? {};
    const handoverFileVo = contractForm.handoverFileVo?.[0] ?? {};
    const data = {
      ...contractForm,
      homeownersId: props.homeownerId,
      contractFile: contractFileVo.id,
      contractFileUrl: contractFileVo.filePath,
      contractFileVo: contractFileVo.id
        ? {
            id: contractFileVo.id,
            filePath: contractFileVo.filePath,
            originalName: contractFileVo.originalName,
          }
        : undefined,
      managementFeeFile: managementFeeFileVo.id,
      managementFeeFileUrl: managementFeeFileVo.filePath,
      managementFeeFileVo: managementFeeFileVo.id
        ? {
            id: managementFeeFileVo.id,
            filePath: managementFeeFileVo.filePath,
            originalName: managementFeeFileVo.originalName,
          }
        : undefined,
      handoverFile: handoverFileVo.id,
      handoverFileUrl: handoverFileVo.filePath,
      handoverFileVo: handoverFileVo.id
        ? {
            id: handoverFileVo.id,
            filePath: handoverFileVo.filePath,
            originalName: handoverFileVo.originalName,
          }
        : undefined,
    };
    saveHomeownersContract(data).then(() => {
      const isEdit = isEditMode(contractForm.id);
      ElMessage.success(isEdit ? "修改成功" : "新增成功");
      emit("saved");
      resetContract();
      close();
    });
  });
}
</script>
